<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<link rel="STYLESHEET" href="lib.css" type='text/css' />
<link rel="SHORTCUT ICON" href="../icons/pyfav.png" type="image/png" />
<link rel='start' href='../index.html' title='Python documentation Index' />
<link rel="first" href="lib.html" title='Python library Reference' />
<link rel='contents' href='contents.html' title="Contents" />
<link rel='index' href='genindex.html' title='Index' />
<link rel='last' href='about.html' title='About this document...' />
<link rel='help' href='about.html' title='About this document...' />
<link rel="next" href="itertools-example.html" />
<link rel="prev" href="module-itertools.html" />
<link rel="parent" href="module-itertools.html" />
<link rel="next" href="itertools-example.html" />
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name='aesop' content='information' />
<title>6.5.1 Itertool functions </title>
</head>
<body>
<div class="navigation">
<div id='top-navigation-panel' xml:id='top-navigation-panel'>
<table align="center" width="100%" cellpadding="0" cellspacing="2">
<tr>
<td class='online-navigation'><a rel="prev" title="6.5 itertools  "
  href="module-itertools.html"><img src='../icons/previous.png'
  border='0' height='32'  alt='Previous Page' width='32' /></a></td>
<td class='online-navigation'><a rel="parent" title="6.5 itertools  "
  href="module-itertools.html"><img src='../icons/up.png'
  border='0' height='32'  alt='Up one Level' width='32' /></a></td>
<td class='online-navigation'><a rel="next" title="6.5.2 Examples"
  href="itertools-example.html"><img src='../icons/next.png'
  border='0' height='32'  alt='Next Page' width='32' /></a></td>
<td align="center" width="100%">Python Library Reference</td>
<td class='online-navigation'><a rel="contents" title="Table of Contents"
  href="contents.html"><img src='../icons/contents.png'
  border='0' height='32'  alt='Contents' width='32' /></a></td>
<td class='online-navigation'><a href="modindex.html" title="Module Index"><img src='../icons/modules.png'
  border='0' height='32'  alt='Module Index' width='32' /></a></td>
<td class='online-navigation'><a rel="index" title="Index"
  href="genindex.html"><img src='../icons/index.png'
  border='0' height='32'  alt='Index' width='32' /></a></td>
</tr></table>
<div class='online-navigation'>
<b class="navlabel">Previous:</b>
<a class="sectref" rel="prev" href="module-itertools.html">6.5 itertools  </a>
<b class="navlabel">Up:</b>
<a class="sectref" rel="parent" href="module-itertools.html">6.5 itertools  </a>
<b class="navlabel">Next:</b>
<a class="sectref" rel="next" href="itertools-example.html">6.5.2 Examples</a>
</div>
<hr /></div>
</div>
<!--End of Navigation Panel-->

<h2><a name="SECTION008510000000000000000"></a><a name="itertools-functions"></a>
<br>
6.5.1 Itertool functions 
</h2>

<p>
The following module functions all construct and return iterators.
Some provide streams of infinite length, so they should only be accessed
by functions or loops that truncate the stream.

<p>
<dl><dt><table cellpadding="0" cellspacing="0"><tr valign="baseline">
  <td><nobr><b><tt id='l2h-1060' xml:id='l2h-1060' class="function">chain</tt></b>(</nobr></td>
  <td><var>*iterables</var>)</td></tr></table></dt>
<dd>
  Make an iterator that returns elements from the first iterable until
  it is exhausted, then proceeds to the next iterable, until all of the
  iterables are exhausted.  Used for treating consecutive sequences as
  a single sequence.  Equivalent to:

<p>
<div class="verbatim"><pre>
     def chain(*iterables):
         for it in iterables:
             for element in it:
                 yield element
</pre></div>
</dl>

<p>
<dl><dt><table cellpadding="0" cellspacing="0"><tr valign="baseline">
  <td><nobr><b><tt id='l2h-1061' xml:id='l2h-1061' class="function">count</tt></b>(</nobr></td>
  <td><var></var><big>[</big><var>n</var><big>]</big><var></var>)</td></tr></table></dt>
<dd>
  Make an iterator that returns consecutive integers starting with <var>n</var>.
  If not specified <var>n</var> defaults to zero.  
  Does not currently support python long integers.  Often used as an
  argument to <tt class="function">imap()</tt> to generate consecutive data points.
  Also, used with <tt class="function">izip()</tt> to add sequence numbers.  Equivalent to:

<p>
<div class="verbatim"><pre>
     def count(n=0):
         while True:
             yield n
             n += 1
</pre></div>

<p>
Note, <tt class="function">count()</tt> does not check for overflow and will return
  negative numbers after exceeding <code>sys.maxint</code>.  This behavior
  may change in the future.
</dl>

<p>
<dl><dt><table cellpadding="0" cellspacing="0"><tr valign="baseline">
  <td><nobr><b><tt id='l2h-1062' xml:id='l2h-1062' class="function">cycle</tt></b>(</nobr></td>
  <td><var>iterable</var>)</td></tr></table></dt>
<dd>
  Make an iterator returning elements from the iterable and saving a
  copy of each.  When the iterable is exhausted, return elements from
  the saved copy.  Repeats indefinitely.  Equivalent to:

<p>
<div class="verbatim"><pre>
     def cycle(iterable):
         saved = []
         for element in iterable:
             yield element
             saved.append(element)
         while saved:
             for element in saved:
                   yield element
</pre></div>

<p>
Note, this member of the toolkit may require significant
  auxiliary storage (depending on the length of the iterable).
</dl>

<p>
<dl><dt><table cellpadding="0" cellspacing="0"><tr valign="baseline">
  <td><nobr><b><tt id='l2h-1063' xml:id='l2h-1063' class="function">dropwhile</tt></b>(</nobr></td>
  <td><var>predicate, iterable</var>)</td></tr></table></dt>
<dd>
  Make an iterator that drops elements from the iterable as long as
  the predicate is true; afterwards, returns every element.  Note,
  the iterator does not produce <em>any</em> output until the predicate
  is true, so it may have a lengthy start-up time.  Equivalent to:

<p>
<div class="verbatim"><pre>
     def dropwhile(predicate, iterable):
         iterable = iter(iterable)
         for x in iterable:
             if not predicate(x):
                 yield x
                 break
         for x in iterable:
             yield x
</pre></div>
</dl>

<p>
<dl><dt><table cellpadding="0" cellspacing="0"><tr valign="baseline">
  <td><nobr><b><tt id='l2h-1064' xml:id='l2h-1064' class="function">groupby</tt></b>(</nobr></td>
  <td><var>iterable</var><big>[</big><var>, key</var><big>]</big><var></var>)</td></tr></table></dt>
<dd>
  Make an iterator that returns consecutive keys and groups from the
  <var>iterable</var>. The <var>key</var> is a function computing a key value for each
  element.  If not specified or is <code>None</code>, <var>key</var> defaults to an
  identity function and returns  the element unchanged.  Generally, the
  iterable needs to already be sorted on the same key function.

<p>
The returned group is itself an iterator that shares the underlying
  iterable with <tt class="function">groupby()</tt>.  Because the source is shared, when
  the <tt class="function">groupby</tt> object is advanced, the previous group is no
  longer visible.  So, if that data is needed later, it should be stored
  as a list:

<p>
<div class="verbatim"><pre>
    groups = []
    uniquekeys = []
    for k, g in groupby(data, keyfunc):
        groups.append(list(g))      # Store group iterator as a list
        uniquekeys.append(k)
</pre></div>

<p>
<tt class="function">groupby()</tt> is equivalent to:

<p>
<div class="verbatim"><pre>
    class groupby(object):
        def __init__(self, iterable, key=None):
            if key is None:
                key = lambda x: x
            self.keyfunc = key
            self.it = iter(iterable)
            self.tgtkey = self.currkey = self.currvalue = xrange(0)
        def __iter__(self):
            return self
        def next(self):
            while self.currkey == self.tgtkey:
                self.currvalue = self.it.next() # Exit on StopIteration
                self.currkey = self.keyfunc(self.currvalue)
            self.tgtkey = self.currkey
            return (self.currkey, self._grouper(self.tgtkey))
        def _grouper(self, tgtkey):
            while self.currkey == tgtkey:
                yield self.currvalue
                self.currvalue = self.it.next() # Exit on StopIteration
                self.currkey = self.keyfunc(self.currvalue)
</pre></div>
  
<span class="versionnote">New in version 2.4.</span>

</dl>

<p>
<dl><dt><table cellpadding="0" cellspacing="0"><tr valign="baseline">
  <td><nobr><b><tt id='l2h-1065' xml:id='l2h-1065' class="function">ifilter</tt></b>(</nobr></td>
  <td><var>predicate, iterable</var>)</td></tr></table></dt>
<dd>
  Make an iterator that filters elements from iterable returning only
  those for which the predicate is <code>True</code>.
  If <var>predicate</var> is <code>None</code>, return the items that are true.
  Equivalent to:

<p>
<div class="verbatim"><pre>
     def ifilter(predicate, iterable):
         if predicate is None:
             predicate = bool
         for x in iterable:
             if predicate(x):
                 yield x
</pre></div>
</dl>

<p>
<dl><dt><table cellpadding="0" cellspacing="0"><tr valign="baseline">
  <td><nobr><b><tt id='l2h-1066' xml:id='l2h-1066' class="function">ifilterfalse</tt></b>(</nobr></td>
  <td><var>predicate, iterable</var>)</td></tr></table></dt>
<dd>
  Make an iterator that filters elements from iterable returning only
  those for which the predicate is <code>False</code>.
  If <var>predicate</var> is <code>None</code>, return the items that are false.
  Equivalent to:

<p>
<div class="verbatim"><pre>
     def ifilterfalse(predicate, iterable):
         if predicate is None:
             predicate = bool
         for x in iterable:
             if not predicate(x):
                 yield x
</pre></div>
</dl>

<p>
<dl><dt><table cellpadding="0" cellspacing="0"><tr valign="baseline">
  <td><nobr><b><tt id='l2h-1067' xml:id='l2h-1067' class="function">imap</tt></b>(</nobr></td>
  <td><var>function, *iterables</var>)</td></tr></table></dt>
<dd>
  Make an iterator that computes the function using arguments from
  each of the iterables.  If <var>function</var> is set to <code>None</code>, then
  <tt class="function">imap()</tt> returns the arguments as a tuple.  Like
  <tt class="function">map()</tt> but stops when the shortest iterable is exhausted
  instead of filling in <code>None</code> for shorter iterables.  The reason
  for the difference is that infinite iterator arguments are typically
  an error for <tt class="function">map()</tt> (because the output is fully evaluated)
  but represent a common and useful way of supplying arguments to
  <tt class="function">imap()</tt>.
  Equivalent to:

<p>
<div class="verbatim"><pre>
     def imap(function, *iterables):
         iterables = map(iter, iterables)
         while True:
             args = [i.next() for i in iterables]
             if function is None:
                 yield tuple(args)
             else:
                 yield function(*args)
</pre></div>
</dl>

<p>
<dl><dt><table cellpadding="0" cellspacing="0"><tr valign="baseline">
  <td><nobr><b><tt id='l2h-1068' xml:id='l2h-1068' class="function">islice</tt></b>(</nobr></td>
  <td><var>iterable, </var><big>[</big><var>start,</var><big>]</big><var> stop </var><big>[</big><var>, step</var><big>]</big><var></var>)</td></tr></table></dt>
<dd>
  Make an iterator that returns selected elements from the iterable.
  If <var>start</var> is non-zero, then elements from the iterable are skipped
  until start is reached.  Afterward, elements are returned consecutively
  unless <var>step</var> is set higher than one which results in items being
  skipped.  If <var>stop</var> is <code>None</code>, then iteration continues until
  the iterator is exhausted, if at all; otherwise, it stops at the specified
  position.  Unlike regular slicing,
  <tt class="function">islice()</tt> does not support negative values for <var>start</var>,
  <var>stop</var>, or <var>step</var>.  Can be used to extract related fields
  from data where the internal structure has been flattened (for
  example, a multi-line report may list a name field on every
  third line).  Equivalent to:

<p>
<div class="verbatim"><pre>
     def islice(iterable, *args):
         s = slice(*args)
         it = iter(xrange(s.start or 0, s.stop or sys.maxint, s.step or 1))
         nexti = it.next()
         for i, element in enumerate(iterable):
             if i == nexti:
                 yield element
                 nexti = it.next()
</pre></div>

<p>
If <var>start</var> is <code>None</code>, then iteration starts at zero.
  If <var>step</var> is <code>None</code>, then the step defaults to one.
  
<span class="versionnote">Changed in version 2.5:
accept <code>None</code> values for default <var>start</var> and
                  <var>step</var>.</span>

</dl>

<p>
<dl><dt><table cellpadding="0" cellspacing="0"><tr valign="baseline">
  <td><nobr><b><tt id='l2h-1069' xml:id='l2h-1069' class="function">izip</tt></b>(</nobr></td>
  <td><var>*iterables</var>)</td></tr></table></dt>
<dd>
  Make an iterator that aggregates elements from each of the iterables.
  Like <tt class="function">zip()</tt> except that it returns an iterator instead of
  a list.  Used for lock-step iteration over several iterables at a
  time.  Equivalent to:

<p>
<div class="verbatim"><pre>
     def izip(*iterables):
         iterables = map(iter, iterables)
         while iterables:
             result = [it.next() for it in iterables]
             yield tuple(result)
</pre></div>

<p>

<span class="versionnote">Changed in version 2.4:
When no iterables are specified, returns a zero length
                  iterator instead of raising a <tt class="exception">TypeError</tt>
		  exception.</span>

<p>
Note, the left-to-right evaluation order of the iterables is guaranteed.
  This makes possible an idiom for clustering a data series into n-length
  groups using "<tt class="samp">izip(*[iter(s)]*n)</tt>".  For data that doesn't fit
  n-length groups exactly, the last tuple can be pre-padded with fill
  values using "<tt class="samp">izip(*[chain(s, [None]*(n-1))]*n)</tt>".

<p>
Note, when <tt class="function">izip()</tt> is used with unequal length inputs, subsequent
  iteration over the longer iterables cannot reliably be continued after
  <tt class="function">izip()</tt> terminates.  Potentially, up to one entry will be missing
  from each of the left-over iterables. This occurs because a value is fetched
  from each iterator in-turn, but the process ends when one of the iterators
  terminates.  This leaves the last fetched values in limbo (they cannot be
  returned in a final, incomplete tuple and they are cannot be pushed back
  into the iterator for retrieval with <code>it.next()</code>).  In general,
  <tt class="function">izip()</tt> should only be used with unequal length inputs when you
  don't care about trailing, unmatched values from the longer iterables.
</dl>

<p>
<dl><dt><table cellpadding="0" cellspacing="0"><tr valign="baseline">
  <td><nobr><b><tt id='l2h-1070' xml:id='l2h-1070' class="function">repeat</tt></b>(</nobr></td>
  <td><var>object</var><big>[</big><var>, times</var><big>]</big><var></var>)</td></tr></table></dt>
<dd>
  Make an iterator that returns <var>object</var> over and over again.
  Runs indefinitely unless the <var>times</var> argument is specified.
  Used as argument to <tt class="function">imap()</tt> for invariant parameters
  to the called function.  Also used with <tt class="function">izip()</tt> to create
  an invariant part of a tuple record.  Equivalent to:

<p>
<div class="verbatim"><pre>
     def repeat(object, times=None):
         if times is None:
             while True:
                 yield object
         else:
             for i in xrange(times):
                 yield object
</pre></div>
</dl>

<p>
<dl><dt><table cellpadding="0" cellspacing="0"><tr valign="baseline">
  <td><nobr><b><tt id='l2h-1071' xml:id='l2h-1071' class="function">starmap</tt></b>(</nobr></td>
  <td><var>function, iterable</var>)</td></tr></table></dt>
<dd>
  Make an iterator that computes the function using arguments tuples
  obtained from the iterable.  Used instead of <tt class="function">imap()</tt> when
  argument parameters are already grouped in tuples from a single iterable
  (the data has been ``pre-zipped'').  The difference between
  <tt class="function">imap()</tt> and <tt class="function">starmap()</tt> parallels the distinction
  between <code>function(a,b)</code> and <code>function(*c)</code>.
  Equivalent to:

<p>
<div class="verbatim"><pre>
     def starmap(function, iterable):
         iterable = iter(iterable)
         while True:
             yield function(*iterable.next())
</pre></div>
</dl>

<p>
<dl><dt><table cellpadding="0" cellspacing="0"><tr valign="baseline">
  <td><nobr><b><tt id='l2h-1072' xml:id='l2h-1072' class="function">takewhile</tt></b>(</nobr></td>
  <td><var>predicate, iterable</var>)</td></tr></table></dt>
<dd>
  Make an iterator that returns elements from the iterable as long as
  the predicate is true.  Equivalent to:

<p>
<div class="verbatim"><pre>
     def takewhile(predicate, iterable):
         for x in iterable:
             if predicate(x):
                 yield x
             else:
                 break
</pre></div>
</dl>

<p>
<dl><dt><table cellpadding="0" cellspacing="0"><tr valign="baseline">
  <td><nobr><b><tt id='l2h-1073' xml:id='l2h-1073' class="function">tee</tt></b>(</nobr></td>
  <td><var>iterable</var><big>[</big><var>, n=2</var><big>]</big><var></var>)</td></tr></table></dt>
<dd>
  Return <var>n</var> independent iterators from a single iterable.
  The case where <code>n==2</code> is equivalent to:

<p>
<div class="verbatim"><pre>
     def tee(iterable):
         def gen(next, data={}, cnt=[0]):
             for i in count():
                 if i == cnt[0]:
                     item = data[i] = next()
                     cnt[0] += 1
                 else:
                     item = data.pop(i)
                 yield item
         it = iter(iterable)
         return (gen(it.next), gen(it.next))
</pre></div>

<p>
Note, once <tt class="function">tee()</tt> has made a split, the original <var>iterable</var>
  should not be used anywhere else; otherwise, the <var>iterable</var> could get
  advanced without the tee objects being informed.

<p>
Note, this member of the toolkit may require significant auxiliary
  storage (depending on how much temporary data needs to be stored).
  In general, if one iterator is going to use most or all of the data before
  the other iterator, it is faster to use <tt class="function">list()</tt> instead of
  <tt class="function">tee()</tt>.
  
<span class="versionnote">New in version 2.4.</span>

</dl>

<p>

<div class="navigation">
<div class='online-navigation'>
<p></p><hr />
<table align="center" width="100%" cellpadding="0" cellspacing="2">
<tr>
<td class='online-navigation'><a rel="prev" title="6.5 itertools  "
  href="module-itertools.html"><img src='../icons/previous.png'
  border='0' height='32'  alt='Previous Page' width='32' /></a></td>
<td class='online-navigation'><a rel="parent" title="6.5 itertools  "
  href="module-itertools.html"><img src='../icons/up.png'
  border='0' height='32'  alt='Up one Level' width='32' /></a></td>
<td class='online-navigation'><a rel="next" title="6.5.2 Examples"
  href="itertools-example.html"><img src='../icons/next.png'
  border='0' height='32'  alt='Next Page' width='32' /></a></td>
<td align="center" width="100%">Python Library Reference</td>
<td class='online-navigation'><a rel="contents" title="Table of Contents"
  href="contents.html"><img src='../icons/contents.png'
  border='0' height='32'  alt='Contents' width='32' /></a></td>
<td class='online-navigation'><a href="modindex.html" title="Module Index"><img src='../icons/modules.png'
  border='0' height='32'  alt='Module Index' width='32' /></a></td>
<td class='online-navigation'><a rel="index" title="Index"
  href="genindex.html"><img src='../icons/index.png'
  border='0' height='32'  alt='Index' width='32' /></a></td>
</tr></table>
<div class='online-navigation'>
<b class="navlabel">Previous:</b>
<a class="sectref" rel="prev" href="module-itertools.html">6.5 itertools  </a>
<b class="navlabel">Up:</b>
<a class="sectref" rel="parent" href="module-itertools.html">6.5 itertools  </a>
<b class="navlabel">Next:</b>
<a class="sectref" rel="next" href="itertools-example.html">6.5.2 Examples</a>
</div>
</div>
<hr />
<span class="release-info">Release 2.5.1, documentation updated on 18th April, 2007.</span>
</div>
<!--End of Navigation Panel-->
<address>
See <i><a href="about.html">About this document...</a></i> for information on suggesting changes.
</address>
</body>
</html>
